package com.jack.leetcode.eachproblem_2020;

/**
 * Created by zhang_j on 2020/11/20
 */
public class 对链表进行插入排序 {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
    public static ListNode insertionSortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode p = head.next;
        ListNode result = new ListNode(-1);
        result.next = new ListNode(head.val);
        while(p != null){
            ListNode tmp = result.next;
            ListNode prev = result;
            while(tmp != null && p.val > tmp.val){
                prev = prev.next;
                tmp = tmp.next;
            }
            prev.next = new ListNode(p.val);
            prev.next.next = tmp;
            p = p.next;

        }
        return result.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(4);
        head.next = new ListNode(2);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(3);
        insertionSortList(head);
    }
}
